'''
提取图片的三色颜色的末位
python3.8
'''
from PIL import Image

class Image_Extract:
    def __init__(self,imagefilename):
        self.color='RGB'                    # RGB  or BGR   or  R  or G  or  B     (red,green,blue)
        self.extr_order = 'ROW'             # ROW  按行取图像像素   or  COL  按列取图像像素  
        self.bit_mask = 0x01                # 取末位
        self.image = Image.open(imagefilename)

    def run(self):
        self.color = 'BGR'
        print(self.extract_data())
        print('========================================')
        self.color = 'RGB'
        print(self.extract_data())
        print('========================================')
        self.color = 'R'
        print(self.extract_data())
        print('========================================')
        self.color = 'G'
        print(self.extract_data())
        print('========================================')
        self.color = 'B'
        print(self.extract_data())
    
    def extract_data(self):
        image = self.image
        pixels = image.load()    #(red,green,blue)
        if self.extr_order == 'ROW':
            i_len = image.height
            j_len = image.width
        else:
            i_len = image.width
            j_len = image.height
        bitStr = ''
        for i in range(i_len):
            for j in range(j_len):   
                bitStr += self.extract_bit(pixels[j,i])
        byteStr_len = len(bitStr) // 8
        byte_list =[]
        for i in range(byteStr_len):
            p = i*8
            byte_list.append(bitStr[p:p+8])
        return "".join([chr(int(i,2)) for i in byte_list])

    def extract_bit(self,pix):    # 0  Red,  1   Green, 2   Blue
        color = self.color.upper()
        bitStr = ''
        i = 0
        for ch in color:
            if   ch == 'R':  i = 0
            elif ch == 'G':  i = 1
            elif ch == 'B':  i = 2 
            bitStr +=  str(pix[i] & self.bit_mask)
        return bitStr

if __name__ == '__main__':
    Image_Extract('6.png').run()                      

